<template>
  <!-- 页面-资源管理 -->
  <div>
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="resourceForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 资源编码 -->
          <Form-item prop="resourceCode" :label="$t('module.resourceManage.resCode')">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm.resourceCode"
              :placeholder="$t('module.resourceManage.enterCode')"
              @on-enter="search"
              @on-blur="codeToUpperCase"
            ></Input>
          </Form-item>

          <!-- 资源名称 -->
          <Form-item prop="resourceName" :label="$t('module.resourceManage.resName')">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm.resourceName"
              :placeholder="$t('module.resourceManage.enterName')"
              @on-enter="search"
            ></Input>
          </Form-item>
          <!-- 状态 -->
          <Form-item prop="enabled" :label="$t('module.functionManage.status')">
            <Select
              :placeholder="$t('common.warning.selectStatus')"
              v-model="searchForm.enabled"
              class="no-borderColor"
              :maxlength="30"
              @on-clear="clearResourceStatus"
              clearable
            >
              <Option v-for="item in enabledForm" :value="item.id" :key="item.enabled">{{ item.enabled }}</Option>
            </Select>
          </Form-item>

          <!-- 类型 -->
          <Form-item prop="type" :label="$t('module.functionManage.resourceType')">
            <Select
              :placeholder="$t('module.functionManage.warning.selectResourceType')"
              v-model="searchForm.resourceTypes"
              class="no-borderColor"
              @on-change="changeResourceTypes"
              @on-clear="clearResourceType"
              clearable
            >
              <Option v-for="item in resourceTypes" :value="item.id" :key="item.resourceTypes">{{
                item.resourceTypes
              }}</Option>
            </Select>
          </Form-item>
          <!-- 是否公开 -->
          <Form-item prop="publicFlag" :label="$t('module.functionManage.isPublic')">
            <Select
              :placeholder="$t('module.functionManage.warning.enterIspublic')"
              v-model="searchForm.publicFlag"
              class="no-borderColor"
              :disabled="searchForm.resourceTypes == 1"
              @on-clear="clearAuthType"
              clearable
            >
              <Option v-for="item in publicEnum" :value="item.id" :key="item.publicFlag">{{ item.publicFlag }}</Option>
            </Select>
          </Form-item>
          <!--          权限模型-->
          <Form-item prop="authType" :label="$t('module.functionManage.permissionModel')">
            <Select
              :placeholder="$t('module.functionManage.warning.permissionModelSelect')"
              v-model="searchForm.authType"
              class="no-borderColor"
              @on-clear="clearPublicFlag"
              clearable
            >
              <Option v-for="item in authTypeList" :value="item.vsiKey" :key="item.vsiKey">{{ item.vsiValue }}</Option>
            </Select>
          </Form-item>
          <!-- 查询\重置按钮 -->
          <Form-item prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="reset" />
          </Form-item>
        </template>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="resourceTable" :config="tableConfig">
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="create" @click="add" />
        <RPButton optType="batch" @click="deleted" />
      </div>
    </InnerPageTable>
  </div>
</template>
<script>
import ResourceEdit from './ResourceEdit.vue'
import CopyResource from './CopyResource.vue'
import AssignResource from './AssignResource.vue'
import { queryResouceList, deleteByIdAndParentId, queryResouceTree } from '@/api/resourceApi.js'
import { searchAppList } from '@/api/applicationApi.js'
import { getRolePostId } from '@/api/postApi.js'
import functionAPI from '@/api/functionAPI.js'
import { mrmColumns } from './columns.js'
import { CoreModuleName } from '@/const.js'
import locales from './locales.js'
import { getValueSetByCode } from '@/api/configApi'

export default {
  name: 'function-resource',
  mixins: [locales],
  props: {
    functionData: {
      type: Object,
      default() {
        return {}
      }
    },
    applicationList: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      enabledForm: [
        { id: 0, enabled: this.$t('common.disable') },
        { id: 1, enabled: this.$t('common.enable') }
      ],
      publicEnum: [
        { id: 1, publicFlag: this.$t('module.resourceManage.public') },
        { id: 2, publicFlag: this.$t('module.resourceManage.notpublic') }
      ],
      resourceTypes: [
        { id: 1, resourceTypes: this.$t('module.resourceManage.uiResource') },
        { id: 2, resourceTypes: this.$t('module.resourceManage.apiResource') },
        { id: 3, resourceTypes: this.$t('module.resourceManage.FlowableModelResource') }
      ],
      functionForm: {},
      // resourceTitle: this.$t("module.resourceManage.resAddresListMaxFifty"),
      modal: false,
      noData: false,
      showDetail: false,
      firstLoading: true,
      searchForm: {
        enabled: null,
        resourceTypes: null,
        publicFlag: null,
        applicationId: '',
        functionId: '',
        parentResourceId: '',
        resourceCode: '',
        resourceName: '',
        authType: ''
      },
      // resourceType: ["UI资源", "API资源", "功能权限"],
      baseData: [],
      selectedData: {},
      selectedMenuID: '',
      selectedMenuName: '',
      defaultProps: {
        children: 'children',
        label: 'functionName'
      },
      node: {},
      nodeElement: {},
      title: '',
      canCreateUI: true,
      canCreateAPI: true,
      canCreateFunc: true,
      isOnlyPublic: false,
      appList: [],
      authTypeList: []
    }
  },
  computed: {
    tableConfig() {
      return {
        loadDataFn: this.queryResouceList,
        columnsFn: mrmColumns.bind(this),
        initParam: this.searchForm,
        autoFirst: false,
        autoMaxHeight: false
      }
    },
    resourceType() {
      return [
        this.$t('module.resourceManage.uiResource'),
        this.$t('module.resourceManage.apiResource'),
        this.$t('module.resourceManage.FlowableModelResource')
      ]
    }
  },
  created: function() {
    // 查询应用
    this.initApplication()
  },
  watch: {
    functionData: {
      immediate: true,
      handler: function(val) {
        this.functionForm = val
        this.searchForm.applicationId = val.applicationId
        this.searchForm.functionId = val.functionId
        this.$nextTick(() => {
          this.$refs['resourceTable'].load(this.searchForm)
        })
      }
    }
  },

  methods: {
    queryResouceList({ responseProcess, param }) {
      if (param.enabled == undefined) {
        param.enabled = null
        param.condition.enabled = null
      }
      if (param.resourceTypes == undefined) {
        param.resourceTypes = null
        param.condition.resourceTypes = null
      } else {
        param.resourceTypes = [this.searchForm.resourceTypes]
        param.condition.resourceTypes = [this.searchForm.resourceTypes]
      }
      if (param.publicFlag == undefined) {
        param.publicFlag = null
        param.condition.publicFlag = null
      }
      queryResouceList(param).then(data => {
        let { records } = data
        records = this.$root.$options.filters['selection-disabled'](records)
        data.records.forEach(item => {
          if (item.resourceType == 1) {
            item.authType = null
          }
        })
        responseProcess(data)
      })
    },
    changeResourceTypes(value) {
      if (value == 1) {
        this.searchForm.publicFlag = null
      }
    },
    search(page = 1) {
      this.codeToUpperCase()
      //刷新列表
      this.$refs['resourceTable'].load(this.searchForm, page)
    },
    reset() {
      this.searchForm.resourceTypes = null
      this.$refs['resourceForm'].resetFields()
      this.search()
    },
    add() {
      // const applicationId = this.node.data.applicationId;
      const { appList } = this
      // 当前应用
      // const currentApplication = appList.find(app => app.clientId === applicationId) || {};

      new this.$pageModal(
        ResourceEdit,
        {
          props: {
            isAdd: true,
            applicationList: this.applicationList,
            functionForm: this.functionForm,
            functionId: this.selectedMenuID,
            parentResourceId: this.searchForm.parentResourceId,
            applicationId: this.functionForm.applicationId,
            applicationName: this.functionForm.applicationName || '',
            canCreateUI: this.canCreateUI,
            canCreateAPI: this.canCreateAPI,
            canCreateFunc: this.canCreateFunc,
            isOnlyPublic: this.isOnlyPublic,
            permissionModelList: this.authTypeList
          }
        },
        data => {
          if (data) {
            // 刷新树
            // data.functionName = data.resourceName;
            // data.children = [];
            // this.node.store.append(data, this.node.data);
            this.search()
          }
        }
      )
    },
    edit(row) {
      const { appList } = this
      // 当前应用
      const currentApplication = appList.find(app => app.clientId === row.applicationId) || {}
      new this.$pageModal(
        ResourceEdit,
        {
          props: {
            isAdd: false,
            applicationList: this.applicationList,
            functionForm: this.functionForm,
            id: row.id,
            functionId: this.selectedMenuID,
            applicationId: row.applicationId,
            applicationName: currentApplication.appName || '',
            resourceObj: row,
            canCreateUI: this.canCreateUI,
            canCreateAPI: this.canCreateAPI,
            canCreateFunc: this.canCreateFunc,
            isOnlyPublic: this.isOnlyPublic,
            parentResourceId: row.parentResourceId,
            permissionModelList: this.authTypeList
          }
        },
        data => {
          if (data) {
            this.search(this.$refs.resourceTable.param.pageNum)
          }
        }
      )
    },
    copy() {
      new this.$pageModal(
        CopyResource,
        {
          props: {
            functionId: this.selectedMenuID,
            parentResourceId: this.searchForm.parentResourceId,
            // applicationId: this.node.data.applicationId ? this.node.data.applicationId : this.node.data.applicationId,
            canCreateUI: this.canCreateUI,
            canCreateAPI: this.canCreateAPI,
            canCreateFunc: this.canCreateFunc,
            isOnlyPublic: this.isOnlyPublic
          }
        },
        data => {
          if (data) {
            this.search()
          }
        }
      )
    },
    assignResource(row) {
      new this.$pageModal(
        AssignResource,
        {
          props: {
            applicationId: row.applicationId,
            parentResourceId: row.id
          }
        },
        data => {}
      )
    },
    deleted(row) {
      if (row.id) {
        new $confirm(this.$t('module.resourceManage.confirmDelete'), this).then(() => {
          deleteByIdAndParentId([{ id: row.id }])
            .then(response => {
              this.$message.success({
                content: this.$t('common.deleteSuccess'),
                duration: 3
              })
              this.search()
              // this.removeRow(selectedRows);
              // this.removeNode(this.node.store, selectedRows);
            })
            .catch(data => {
              this.$message.error({
                content: data.message,
                duration: 3
              })
            })
        })
      } else {
        let selectedIds = this.getSelectedIds()
        if (selectedIds.length == 0) {
          this.$message.error({
            content: this.$t('module.resourceManage.selectDeletion'),
            duration: 3
          })
          return
        }
        let selectedRows = this.$refs['resourceTable'].getSelectioned()
        new $confirm(this.$t('module.resourceManage.confirmDelete'), this).then(() => {
          deleteByIdAndParentId(selectedIds)
            .then(response => {
              this.$message.success({
                content: this.$t('common.deleteSuccess'),
                duration: 3
              })
              this.search()
              // this.removeRow(selectedRows);
              // this.removeNode(this.node.store, selectedRows);
            })
            .catch(data => {
              this.$message.error({
                content: data.message,
                duration: 3
              })
            })
        })
      }
    },
    getSelectedIds() {
      let list = this.$refs['resourceTable'].getSelectioned() || []
      let ids = []
      for (let u of list) {
        ids.push({ id: u.id, parentResourceId: u.parentResourceId })
      }
      return ids
    },
    initApplication() {
      getValueSetByCode('SYS_FUNCTION_AUTH_TYPE').then(res => {
        this.authTypeList = res.data
      })
    },
    initMenus(index, appId) {
      functionAPI.queryFunctionList(appId).then(data => {
        this.baseData[index].children = data
        let publicAPI = {
          applicationId: appId,
          id: index,
          functionName: '公共API',
          children: [],
          publicFlagAPI: true
        }
        this.baseData[index].children.push(publicAPI)
      })
    },
    loadNode(node, resolve) {
      if (node.level == 0) {
        // 隐藏根节点
        return
      }

      if (node.data.functionType == '1') {
        // 节点是菜单目录
        resolve(node.data.children)
      } else if (node.data.functionType == '0') {
        // 节点是菜单
        this.loadResource(node.data, resolve)
      } else if (node.data.resourceType) {
        // 节点是资源
        node.data.children.forEach(resource => {
          resource.functionName = resource.resourceName
        })
        resolve(node.data.children)
      } else {
        // 未知类型节点
        resolve(node.data.children)
      }
    },
    loadResource(parentNode, resolve) {
      let param = { functionId: parentNode.id }
      // this.$store
      //   .dispatch("QueryResouceTree", param)
      queryResouceTree(param)
        .then(res => {
          const { data } = res
          data.forEach(resource => {
            parentNode.children.push(resource)
            resource.functionName = resource.resourceName
          })
          resolve(data)
        })
        .catch(data => {
          this.$message.error({
            content: data.message,
            duration: 3
          })
        })
    },
    clearResourceStatus() {
      this.searchForm.enabled = null
    },
    clearResourceType() {
      this.searchForm.resourceTypes = null
    },
    clearAuthType() {
      this.searchForm.authType = null
    },
    clearPublicFlag() {
      this.searchForm.publicFlag = null
    },
    codeToUpperCase() {
      this.searchForm.resourceCode = this.searchForm.resourceCode.toUpperCase()
    }
  }
}
</script>
<style lang="less">
.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 12px;
}

.MenuResourceManage-page {
  .invalid {
    color: #bcbcbc;
  }
}
</style>
